package follow.juc.heima.day8;

import jdk.nashorn.internal.ir.CallNode;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class Demo4ABA {
    private static AtomicInteger ai = new AtomicInteger(100);
    private static AtomicStampedReference air = new AtomicStampedReference(100, 1);

    public static void main(String[] args) throws InterruptedException {

        Thread at1 = new Thread(new Runnable() {
            @Override
            public void run() {
                ai.compareAndSet(100, 110);
                ai.compareAndSet(110, 100);
            }
        });
        Thread at2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //为了让线程1先执行完，等一会
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("AtomicInteger:" + ai.compareAndSet(100, 120));
                System.out.println("执行结果:" + ai.get());
            }
        });
        at1.start();
        at2.start();

        //顺序执行，AtomicInteger案例先执行
        at1.join();
        at2.join();

        Thread tsf1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                air.compareAndSet(100, 110, air.getStamp(), air.getStamp() + 1);
                air.compareAndSet(110, 100, air.getStamp(), air.getStamp() + 1);
            }
        });


        Thread tsf2 = new Thread(new Runnable() {
            @Override
            public void run() {
                int stamp = air.getStamp();

                try {
                    TimeUnit.MILLISECONDS.sleep(100);     //线程tsf1执行完
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("AtomicStampedReference:" + air.compareAndSet(100, 120, stamp, stamp + 1));
                int[] stampArr = {stamp + 1};
                System.out.println("执行结果：" + air.get(stampArr));

            }
        });
        tsf1.start();
        tsf2.start();
    }
}
